<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="150px">
      <el-form-item label="异常分类" prop="typeId">
        <el-cascader clearable v-model="queryParams.typeId" :options="sortType" :props="{
          expandTrigger: 'hover',
          value: 'id',
          label: 'excepDesc',
          children: 'childList',
        }" style="width: 100%" />
      </el-form-item>
      <el-form-item label="SN编码" prop="snCode">
        <el-input v-model="queryParams.snCode" placeholder="请输入SN编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工单编码" prop="workorderCode">
        <el-input v-model="queryParams.workorderCode" placeholder="请输入工单编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品编码" prop="productCode">
        <el-input v-model="queryParams.productCode" placeholder="请输入产品编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="规格型号" prop="productSpc">
        <el-input v-model="queryParams.productSpc" placeholder="请输入规格型号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="跟进日期">
        <el-date-picker v-model="queryParams.time" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']"></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="异常分类" width="200" align="center" prop="excepDesc" />
      <el-table-column label="异常状态" align="center" prop="flowStatusName" />
      <el-table-column label="SN编码" align="center" prop="snCode" />
      <el-table-column label="工单编码" align="center" prop="workorderCode" />
      <el-table-column label="物料编码" align="center" prop="productCode" />
      <el-table-column label="物料名称" align="center" prop="productName" />
      <el-table-column label="规格型号" align="center" prop="productSpc" />
      <el-table-column label="批次号" align="center" prop="batchCode" />
      <el-table-column label="批号名称" align="center" prop="batchName" />
      <el-table-column label="工单数量" align="center" prop="quantity" />
      <el-table-column label="判定人" align="center" prop="judgeName" />
      <el-table-column label="判定时间" align="center" prop="judgeTime" />
      <el-table-column label="跟进人" align="center" prop="followName" />
      <el-table-column label="跟进时间" align="center" prop="followTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-show="scope.row.source == '' || scope.row.source == null" size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['exception:follow:push']">下推</el-button>
          <!--add begin by zyj 2025-01-15 IQC质检不合格流程: 系统发起提报-30E-计划-采购-品质部经理-->
          <!-- <el-button :disabled="scope.row.source != '' || scope.row.flowStatus == 2" size="mini" type="text"
            icon="el-icon-edit" @click="handleAudit(scope.row)" v-hasPermi="['exception:follow:audit']">审核</el-button> -->
          <!--add end by zyj 2025-01-15 IQC质检不合格流程: 系统发起提报-30E-计划-采购-品质部经理-->
          <!-- edit 更换审核按钮使用判定条件 -->
          <el-button v-show="scope.row.source != '' && scope.row.flowStatus == 2 && currentUser == scope.row.auditPerson" size="mini" type="text" icon="el-icon-edit" @click="handleAudit(scope.row)">审核</el-button>
          <!-- edit end 更换审核按钮使用判定条件 -->
          <!-- :disabled="scope.row.flowStatus != 1 && scope.row.flowStatus != 2" -->
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:record:remove']"
          >删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    <!-- 添加或修改异常填报对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <!-- style="display: flex; flex-wrap: wrap" -->
        <el-form-item label="下推用户" prop="handleName" style="flex: 0 0 50%">
          <!-- edit begin by zyj 2024/11/05 多选-->
          <!-- <el-autocomplete
            value-key="userName"
            v-model="handleName"
            :fetch-suggestions="querySearchAsync"
            
            placeholder="请选择下推用户"
            @select="handleSelectAdmin"
            @input="(value) => handleInputAdmin(value)"
          ></el-autocomplete> -->
          <el-select v-model="userIds" filterable multiple placeholder="请选择下推用户">
            <el-option v-for="(item, index) in adminList" :key="index" :label="item.userName" :value="item.userId">
            </el-option>
          </el-select>
          <!-- edit end by zyj 2024/11/05 多选-->
        </el-form-item>
        <!-- add begin by zyj 2024/11/05 添加指导处理意见-->
        <el-form-item label="指导处理意见" prop="guideRemark" style="flex: 0 0 50%">
          <el-input v-model="form.guideRemark" type="textarea" placeholder="请输入指导处理意见" :rows="3" style="width: 100%" />
        </el-form-item>
        <!-- add begin by zyj 2024/11/05 添加指导处理意见-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <AuditDialog @success="auditSuccess" ref="auditDialog"></AuditDialog>
  </div>
</template>

<script>
import {
  listRecord,
  getRecord,
  delRecord,
  addRecord,
  updateRecord,
  getTreeList,
  getWorkorderBySnCode,
  getAdminList,
  pushDown,
} from "@/api/system/follow";
import AuditDialog from "../components/auditDialog.vue";
export default {
  name: "ExceptionFollow",
  dicts: ["sys_flow_status"],
  components: {
    AuditDialog,
  },
  data() {
    return {
      currentUser: this.$store.state.user.name,//当前登录人
      selection: [],
      typeVal: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 异常填报表格数据
      recordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        typeId: null,
        snCode: null,
        workorderId: null,
        oneLevelId: null,
        twoLevelId: null,
        threeLevelId: null,
        judgeBy: null,
        judgeTime: null,
        followBy: null,
        followTime: null,
        handleBy: null,
        handleTime: null,
        confirmBy: null,
        confirmTime: null,
        abnormalWorkinghours: null,
        flowStatus: null,
      },
      // 表单参数
      form: {
        handleBy: null,
        guideRemark: null,
        id: null,
      },
      // 表单校验
      rules: {
        handleName: [],
      },
      sortType: [],
      adminList: [],
      timeout: null,
      userId: null,
      //edit begin by zyj  2024/11/05 下推多选
      // handleName: null,
      userIds: [],
      //edit end by zyj  2024/11/05 下推多选
    };
  },
  created() {
    this.getList();
    this.getTreeList();
    this.getAdminList();
  },
  // watch: {
  //   handleName(newVal, oldVal) {
  //     console.log(newVal, oldVal, this.userId);
  //     setTimeout(() => {
  //       console.log(!oldVal, oldVal);
  //       if (!oldVal) return;
  //       console.log("清空了");
  //       this.userId = null;
  //     });
  //   },
  // },
  methods: {
    //add begin by zyj 2025-01-15 IQC质检不合格流程: 系统发起提报-30E-计划-采购-品质部经理
    auditSuccess() {
      this.getList();
    },
    handleAudit(row) {
      this.$refs.auditDialog.show(row.id);
    },
    //add end by zyj 2025-01-15 IQC质检不合格流程: 系统发起提报-30E-计划-采购-品质部经理
    handleInputAdmin(e) {
      this.userId = null;
      // console.log("!!!", e);
    },
    handleSelectAdmin(val) {
      console.log(val);
      this.form.handleName = val.handleName;
      // this.handleName = val.handleName;
      this.userId = val.userId;
      // console.log("???");
    },
    getAdminList() {
      let param = {
        pageNum: 1,
        pageSize: 10000,
      };
      getAdminList(param).then((res) => {
        this.adminList = res.rows ? res.rows : [];
      });
    },
    querySearchAsync(queryString, cb) {
      var restaurants = this.adminList;
      var results = queryString
        ? restaurants.filter(this.createStateFilter(queryString))
        : restaurants;
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 300 * Math.random());
    },
    createStateFilter(queryString) {
      return (state) => {
        return state.userName.includes(queryString);
      };
    },
    handleGetWorkorderBySnCode() {
      //50240412175
      const param = {
        snCode: this.form.snCode, //SN码
      };
      getWorkorderBySnCode(param).then((res) => {
        const data = res.data ? res.data : {};
        this.form.workorderCode = data.workorderCode;
        this.form.productCode = data.productCode;
        this.form.productName = data.productName;
        this.form.productSpc = data.productSpc;
        this.form.batchCode = data.batchCode;
        this.form.batchName = data.batchName;
        this.form.quantity = data.quantity;
      });
    },
    getTreeList() {
      getTreeList().then((res) => {
        let data = res.data ? res.data : [];
        data.forEach((item) => {
          item.childList.forEach((item2) => {
            delete item2.childList;
          });
        });
        this.sortType = data;
        // this.sortType = data.map(item => {
        //   item.childList = newItem.childList.map(item2 => {
        //     delete item2.childList
        //     return item2
        //   })
        //   return item
        // })
      });
    },
    /** 查询异常填报列表 */
    getList() {
      this.loading = true;
      if (this.queryParams.typeId && this.queryParams.typeId.length) {
        this.queryParams.typeId = this.queryParams.typeId[1];
      }
      listRecord(this.queryParams).then((response) => {
        this.recordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        handleBy: null,
        id: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      console.log(this.queryParams, "=====queryParams===");
      if (this.queryParams.time) {
        this.queryParams["followTimeBegin"] = this.queryParams.time[0];
        this.queryParams["followTimeEnd"] = this.queryParams.time[1];
      } else {
        this.queryParams["followTimeBegin"] = null;
        this.queryParams["followTimeEnd"] = null;
      }
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.time = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selection = selection;
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加异常填报";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      let data = this.deepClone(row);
      if (row.id) {
        const data = this.deepClone(row);
      } else {
        data = this.deepClone(this.selection[0]);
      }
      this.form.id = data.id;
      // this.handleName = data.handleName;
      this.userId = data.handleBy;
      this.open = true;
      this.title = "下推";
    },
    /** 提交按钮 */
    //edit begin by zyj 2024/11/05 下推多选

    // submitForm() {
    //   if (!this.userId) return this.$message.error("下推人员必填");
    //   const param = {
    //     id: this.form.id,
    //     handleBy: this.userId,
    //   };
    //   // console.log(param);
    //   pushDown(param).then((response) => {
    //     this.$modal.msgSuccess("修改成功");
    //     this.open = false;
    //     this.getList();
    //   });
    // },
    submitForm() {
      if (!this.userIds || this.userIds.length == 0) return this.$message.error("下推人员必填");
      const param = {
        id: this.form.id,
        userIds: this.userIds,
        guideRemark: this.form.guideRemark
      };
      console.log(param);
      pushDown(param).then((response) => {
        this.$modal.msgSuccess("修改成功");
        this.open = false;
        this.getList();
      });
    },
    //edit end by zyj 2024/11/05 下推多选
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除异常填报编号为"' + ids + '"的数据项？')
        .then(function () {
          return delRecord(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/record/export",
        {
          ...this.queryParams,
        },
        `record_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style scoped>
.sort .el-cascader {
  width: 100%;
}
</style>
